package com.example.home_app.base.equipmentFragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.frame.mvp.CommonBaseFragment
import com.android.widget.PopupWindow.CommonPopupWindow
import com.android.widget.dialog.ConfirmDialog
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.home_app.R
import com.example.home_app.adapter.DriveKinectAdapter
import com.example.home_app.base.Onenet_online.Online_json
import com.example.home_app.base.activity.AddDeviceActivity
import com.example.home_app.base.activity.LedActivity
import com.example.home_app.base.activity.LineChartActivity
import com.example.home_app.databinding.FragmentKitchenSbBinding
import com.example.home_app.http.AATest.ApiService
import com.example.home_app.http.AATest.UrlConstant
import com.example.home_app.http.ExceptionUtil
import com.example.home_app.http.RetrofitFactory
import com.example.home_app.http.SchedulerUtil
import com.example.home_app.util.SbParameter
import com.example.home_app.util.SizeUtil
import com.example.home_app.util.State
import com.example.home_app.util.Status
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import java.util.ArrayList
import java.util.HashMap

/**
 * Created by dell on 2021/8/10.
 */

class KitchenSbFragment : CommonBaseFragment<FragmentKitchenSbBinding>(){
    private var mDriveAdapter: DriveKinectAdapter? = null
    private val list = ArrayList<Map<String, Any>>()
    var map: Map<String, Any>? = null
    var sum = ""
    companion object {
        fun newInstance() = KitchenSbFragment()
    }

    override fun handleView(savedInstanceState: Bundle?) {
        mRecyclerView?.setHasFixedSize(true)
        mRecyclerView?.layoutManager = LinearLayoutManager(context)
        intDate()

    }
    private fun intDate(){
        showLoadingDialog()
        Handler(Looper.getMainLooper()).postDelayed({
            if (State.DeviceIDKitchen != ""){
                getLoadingLayout()?.loadComplete()
                accessUrlRxJava(UrlConstant.ONE_NET_URL)
                sum = State.DeviceIDBathroom.toString()
            }else{
                getLoadingLayout()?.loadEmpty()
            }

        }, 1500)
        super.onResume()
    }
    override fun onResume(){
        super.onResume()
        if (sum != State.DeviceIDKitchen ){
            showLoadingDialog()
            Handler(Looper.getMainLooper()).postDelayed({
                accessUrlRxJava(UrlConstant.ONE_NET_URL)
                sum = State.DeviceIDKitchen.toString()
                getLoadingLayout()?.loadComplete()
            }, 1500)
        }
    }
    override fun initListener() {
        //添加设备
        binding.FloatingActionButton.setOnClickListener {
            State.SCENE = "Kitchen"
            startActivity(AddDeviceActivity::class.java)
        }
        //空数据时点击按钮回调
        getLoadingLayout()?.setOnEmptyListener {
            State.SCENE = "Kitchen"
            startActivity(AddDeviceActivity::class.java)

        }
        //点击重试
        getLoadingLayout()?.setOnFailListener {
            showLoadingDialog()
            Handler(Looper.getMainLooper()).postDelayed({
                getLoadingLayout()?.loadComplete()
            }, 1500)
        }
    }
    var datalist = 0
    private fun initAdapter() {

        mDriveAdapter = DriveKinectAdapter(list)
        //打开动画
        mDriveAdapter!!.animationEnable = true
        mDriveAdapter!!.addChildClickViewIds(R.id.line,R.id.ImageView)
        mDriveAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            var content: String? = null

            datalist = position
            var status = adapter.getItem(position) as Status
            when (view.id) {
                R.id.line -> if (list[position]["name"].toString().indexOf("led") != - 1) {
                    val bundle = Bundle()
                    bundle.putString(LedActivity.EXTRA_ID, list[position]["id"].toString())
                    bundle.putString(LedActivity.EXTRA_MAME, list[position]["name"].toString())
                    bundle.putString(LedActivity.EXTRA_ONLINE, list[position]["online"].toString())
                    startActivity(LedActivity::class.java, bundle)
                }
                else if(list[position]["name"].toString().indexOf("DHT11") != - 1)
                {
                    val bundle = Bundle()
                    bundle.putString(LineChartActivity.EXTRA_ID, list[position]["id"].toString())
                    bundle.putString(LineChartActivity.EXTRA_MAME, list[position]["name"].toString())
                    bundle.putString(LineChartActivity.EXTRA_ONLINE, list[position]["online"].toString())
                    startActivity(LineChartActivity::class.java, bundle)
                }
                R.id.ImageView -> showFullWindow(View(context))
                else -> {
                }
            }
            if (content != null) {
                showToast(content)
            }

        }
        mDriveAdapter!!.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn)
        mRecyclerView?.adapter = mDriveAdapter
    }
    //向左弹出
    private var mPopupWindow: CommonPopupWindow? = null
    //全屏弹出
    private fun showFullWindow(view: View) {

        if (mPopupWindow != null && mPopupWindow!!.isShowing)
            return
        mPopupWindow = activity?.let { it ->
            CommonPopupWindow.Builder(it)

                .setContentView(R.layout.layout_popup_window_full)
                .setViewParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setBackGroundAlpha(0.8f)
                .setAnimationStyle(R.style.BottomAnimation)
                .setOnViewListener { holder, popupWindow ->

                    holder.setOnClickListener(R.id.set_bt) {
                        showToast("设置")

                        popupWindow.dismiss()
                    }
                    holder.setOnClickListener(R.id.deleat_bt) {
                        showMultiDialog()
                        popupWindow.dismiss()
                    }
                    holder.setOnClickListener(R.id.cancel) {
                        showToast("取消")
                        popupWindow.dismiss()
                    }
                    //view.findViewById<TextView>(R.id.sai_id).text = list[datalist]["id"].toString()
                }.build()
        }

        mPopupWindow!!.showAtLocation(view, Gravity.BOTTOM, 0, 0)
    }
    //双按钮Dialog
    private fun showMultiDialog() {
        fragmentManager?.let { it ->
            ConfirmDialog.newInstance("提示", "是否确认删除设备？")
                .setOnConfirmListener {
                    it?.dismiss()
                    map = list[datalist]
                    list.remove(map)
                    SbParameter.KitchenSUM --
                    showToast("删除成功")
                    Handler(Looper.getMainLooper()).postDelayed({
                        initAdapter()
                    }, 300)
                }
                .setOnCancelListener {
                    it?.dismiss()
                    //showToast("取消")
                }
                .setOutsideCancelable(true)
                .setHorizontalMargin(SizeUtil.dp2px(60f).toInt())
                .show(it)
        }
    }
    /**
     * TODO RX思维
     * 获取设备状态
     */
    //访问网址，Retrofit + RxJava
    private fun accessUrlRxJava(url: String) {
        RetrofitFactory.instance.createService(ApiService::class.java, url)
            .getMessage(State.ApiKey, State.DeviceIDKitchen)
            ?.compose(SchedulerUtil.ioToMain())
            //            ?.subscribeOn(Schedulers.io())// 在IO线程进行网络请求
            //            ?.observeOn(AndroidSchedulers.mainThread())// 回到主线程 处理请求结果
            ?.subscribe(object : Observer<Online_json?> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(online_json: Online_json) {
                    //showToast("访问成功！")
                    val devices = online_json.getData() !!.getDevices()
                    var o: String
                    println(devices)
                    //SbParameter.HISTORYLIST = online_json.getData() !!.getTotal_count()
                    if (SbParameter.KitchenSUM < online_json.getData() !!.getTotal_count()) {
                        val j: Int = online_json.getData() !!.getTotal_count() - SbParameter.KitchenSUM
                        for (i in 0 until j) {
                            map = HashMap()
                            (map as HashMap<String, Any>)["id"] = "请刷新"
                            (map as HashMap<String, Any>)["name"] = "请刷新"
                            (map as HashMap<String, Any>)["online"] = "请刷新"
                            list.add(map as HashMap<String, Any>)
                        }
                        SbParameter.KitchenSUM = online_json.getData() !!.getTotal_count()
                    }

                    for (i in 0 until online_json.getData() !!.getTotal_count()) {
                        o = if (devices !![i].getOnline()) {
                            "√"
                        } else {
                            "×"
                        }
                        map = list[i]
                        (map as HashMap<String, Any>)["id"] = devices[i].getId().toString()
                        (map as HashMap<String, Any>)["name"] = devices[i].getTitle().toString()
                        (map as HashMap<String, Any>)["online"] = o
                    }
                        initAdapter()

                }

                override fun onError(e: Throwable) {
                    showToast(ExceptionUtil.convertExceptopn(e))
                    e.printStackTrace()
                }

            })
    }
}